import {getArticleDetail, getArticleType, getUserInfo } from './actionType'
import {get, post} from '../utils/requestUtil'
import {message} from 'antd'
import ipPort from "../common/ipPort";
import md5 from 'js-md5';

let userInfo = {
    username: '',
    account: '',
    wechat: '',
    QQ: '',
    github: '',
    keywords: '',
    description: '',
    sendword: '',
    userId: ''
}

//获取文章类型
export function GET_TYPE(data) {
    return async dispatch => {
        try {
            let res = await get(ipPort + '/api/default/articleType', {});
            if (res.success) {
                dispatch({type: getArticleType, data: res.results})
            } else {
                dispatch({type: getArticleType, data: []});
                message.error(`获取文章类型失败，异常信息为：${res.code}`)
            }

        } catch (e) {
            dispatch({type: getArticleType, data: []});
            message.error(`获取文章类型失败，异常信息为：${e}`)
        }
    }
}

export function GET_INFO(data) {
    return async dispatch => {
       
        try {
            let res = await get(ipPort + '/api/admin/info', data );
            if (res.success) {
                let Info = decodeURIComponent(escape(window.atob(res['userInfo'])))
                dispatch({type: getUserInfo, data: JSON.parse(Info) })
            } else {
                dispatch({type: getUserInfo, data: userInfo })
            }
        } catch (e) {
             dispatch({type: getUserInfo, data: userInfo })
        }
    }
}

export function LOGIN(param) {
     return async dispatch => {
        try {
            let res = await post(ipPort + '/api/admin/login', { account: param.account, password: md5(param.password), remember: true });
            let data = res.data
            if (data.success) {
                let Info = decodeURIComponent(escape(window.atob(res.data['userInfo'])))
                dispatch({type: getUserInfo, data: JSON.parse(Info) })
                message.success('登录成功')
            } else {
                dispatch({type: getUserInfo, data: userInfo })
                message.error(`登录失败，异常信息为：${data.code}`)
            }
        } catch (e) {
            dispatch({type: getUserInfo, data: userInfo })
            message.error(`登录失败，异常信息为：${e}`)
        }
    }
}

//获取文章详情数据
export function SET_DETAIL(data) {
    return {type: getArticleDetail, data}
}

export function LOGOUT(value) {
      return async dispatch => {
        try {
            let res = await post(ipPort + '/api/admin/logout', value);
            let data = res.data
            if (data.success) {
                dispatch({type: getUserInfo, data: userInfo })
                message.success('注销成功')
            } else {
                message.error(`注销失败，异常信息为：${data.code}`)
            }
        } catch (e) {
            message.error(`注销失败，异常信息为：${e}`)
        }
    }
}
